<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="送货单号" prop="deliveryNo">
        <el-input
          v-model="queryParams.deliveryNo"
          placeholder="请输入送货单编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="客户名称" prop="customerName">
        <el-input
          v-model="queryParams.customerName"
          placeholder="请输入客户名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="送货状态" prop="deliveryStatus">
        <el-select v-model="queryParams.deliveryStatus" placeholder="请选择送货状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_delivery_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="送货日期">
        <el-date-picker
          v-model="daterangeDeliveryDate"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 工具栏 -->
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['test:delivery:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['test:delivery:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['test:delivery:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['test:delivery:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 数据表格 -->
    <el-table v-loading="loading" :data="deliveryList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="送货单编号" align="left" prop="deliveryNo" width="140" :show-overflow-tooltip="true" />
      <el-table-column label="客户编码" align="left" prop="customerCode" width="120" :show-overflow-tooltip="true" />
      <el-table-column label="客户名称" align="left" prop="customerName" :show-overflow-tooltip="true" min-width="160" />
      <el-table-column label="送货人员" align="center" prop="deliveryPerson" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="送货日期" align="center" prop="deliveryDate" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.deliveryDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="总金额" align="center" prop="totalAmount" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.totalAmount ? '¥' + scope.row.totalAmount.toFixed(2) : '¥0.00' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="送货状态" align="center" prop="deliveryStatus" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_delivery_status" :value="scope.row.deliveryStatus"/>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-switch v-model="scope.row.status" active-value="0" inactive-value="1" @change="handleStatusChange(scope.row)"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="220" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)" v-hasPermi="['test:delivery:query']">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['test:delivery:edit']">修改</el-button>
          <el-dropdown size="mini" @command="(command) => handleCommand(command, scope.row)" v-hasPermi="['test:delivery:edit']" style="margin-left:10px">
            <el-button size="mini" type="text">
              更多<i class="el-icon-arrow-down el-icon--right"></i>
            </el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="delivery" icon="el-icon-truck">送货中</el-dropdown-item>
              <el-dropdown-item command="delivered" icon="el-icon-circle-check">已送达</el-dropdown-item>
              <el-dropdown-item command="signed" icon="el-icon-success">已签收</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 分页 -->
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <!-- 添加或修改对话框 -->
    <el-drawer :title="title" :visible.sync="open" direction="rtl" size="80%" :before-close="cancel">
      <div style="padding: 20px">
        <el-form ref="form" :model="form" :rules="rules" label-width="80px">
          <el-row>
            <el-col :span="12">
              <el-form-item label="送货单号">
                <el-input v-model="form.deliveryNo" placeholder="系统自动生成" :disabled="true" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="送货人员" prop="deliveryPerson">
                <el-input v-model="form.deliveryPerson" placeholder="请输入送货人员" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="客户选择" prop="customerId">
                <el-select v-model="form.customerId" placeholder="请选择客户" clearable @change="handleCustomerChange" filterable>
                  <el-option
                    v-for="customer in customerOptions"
                    :key="customer.customerId"
                    :label="customer.customerName"
                    :value="customer.customerId"
                  >
                    <span style="float: left">{{ customer.customerName }}</span>
                    <span style="float: right; color: #8492a6; font-size: 13px">{{ customer.customerCode }}</span>
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="送货日期" prop="deliveryDate">
                <el-date-picker clearable
                  v-model="form.deliveryDate"
                  type="datetime"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  placeholder="请选择送货日期">
                </el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="送货状态" prop="deliveryStatus">
                <el-select v-model="form.deliveryStatus" placeholder="请选择送货状态">
                  <el-option
                    v-for="dict in dict.type.sys_delivery_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="总金额">
                <el-input v-model="totalAmountDisplay" :disabled="true" placeholder="自动计算">
                  <template slot="prepend">¥</template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <!-- 送货单明细 -->
          <el-divider content-position="left">送货单明细</el-divider>
          <el-row>
            <el-col :span="24">
              <el-button type="primary" size="small" @click="handleAddDetail">添加明细</el-button>
              <el-table :data="form.deliveryDetailList" style="margin-top: 10px; width: 100%" border>
                <el-table-column type="index" label="序号" width="50" align="center" />
                <el-table-column label="状态" width="80" align="center" v-if="false">
                  <template slot-scope="scope">
                    <el-tag v-if="scope.row.detailId && !scope.row._isNew" type="info" size="mini">已存在</el-tag>
                    <el-tag v-else-if="scope.row._isNew" type="success" size="mini">新增</el-tag>
                    <el-tag v-else type="warning" size="mini">未保存</el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="物料选择" min-width="280">
                  <template slot-scope="scope">
                    <el-select 
                      size="small" 
                      v-model="scope.row.materialId" 
                      placeholder="请选择物料" 
                      @change="handleMaterialChange(scope.$index)" 
                      filterable
                      popper-class="material-select-dropdown"
                      style="width: 100%"
                    >
                      <el-option
                        v-for="material in materialOptions"
                        :key="material.materialId"
                        :label="material.materialName"
                        :value="material.materialId"
                        :disabled="isMaterialSelected(material.materialId, scope.$index)"
                      >
                        <div class="material-option-content" :class="{ 'material-disabled': isMaterialSelected(material.materialId, scope.$index) }">
                          <span class="material-name">{{ material.materialName }}</span>
                          <div class="material-info">
                            <div class="material-code">{{ material.materialCode }}</div>
                            <div class="material-price">{{ material.unitOfMeasure }} | ¥{{ material.salePrice || 0 }}</div>
                          </div>
                          <span v-if="isMaterialSelected(material.materialId, scope.$index)" class="material-selected-tag">已选择</span>
                        </div>
                      </el-option>
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column label="物料编码" prop="materialCode" width="110" />
                <el-table-column label="数量" width="120">
                  <template slot-scope="scope">
                    <el-input-number controls-position="right" style="width: 100%;" v-model="scope.row.quantity" :min="0" :precision="0" @change="calculateRowTotal(scope.$index)" size="small" />
                  </template>
                </el-table-column>
                <el-table-column label="单位" prop="unit" width="70" align="center" />
                <el-table-column label="单价" width="120" align="center">
                  <template slot-scope="scope">
                    <span style="color: #606266; font-weight: 500;">¥{{ scope.row.unitPrice ? scope.row.unitPrice.toFixed(2) : '0.00' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="小计" width="130" align="center">
                  <template slot-scope="scope">
                    <span style="color: #E6A23C; font-weight: 500;">{{ scope.row.totalPrice ? '¥' + scope.row.totalPrice.toFixed(2) : '¥0.00' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="70" align="center">
                  <template slot-scope="scope">
                    <el-button type="text" size="small" @click="handleDeleteDetail(scope.$index)" :disabled="form.deliveryDetailList.length <= 1" style="color: #F56C6C;">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          
          <!-- 明细操作提示 -->
          <el-row style="margin-top: 10px">
            <el-col :span="24">
              <el-alert
                title="明细操作说明"
                type="info"
                :closable="false"
                show-icon>
                <template slot="description">
                  <div>• 添加明细：点击"添加明细"按钮新增一行</div>
                  <div>• 选择物料：选择物料后自动填充物料编码、名称、单位和单价（单价不可修改）</div>
                  <div>• 物料唯一：同一送货单中每个物料只能选择一次，已选择的物料将显示为禁用状态</div>
                  <div>• 修改数量：调整数量后自动计算小计，单价从物料主数据获取不可修改</div>
                  <div>• 删除明细：点击"删除"按钮移除明细（已存在的明细将在保存时真正删除）</div>
                  <div>• 金额计算：数量×单价=小计，所有小计之和=总金额</div>
                </template>
              </el-alert>
            </el-col>
          </el-row>
        </el-form>
        <div style="text-align: left; margin-top: 20px; margin-left: 0;">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </div>
    </el-drawer>

    <!-- 详情对话框 -->
    <el-drawer :visible.sync="detailOpen" direction="rtl" size="75%">
      <div slot="title" style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
        <span>送货单详情</span>
        <el-button type="primary" size="small" icon="el-icon-printer" @click="handlePrint">打印送货单</el-button>
      </div>
      <div style="padding: 20px">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="送货单编号">{{ detailForm.deliveryNo }}</el-descriptions-item>
          <el-descriptions-item label="客户名称">{{ detailForm.customerName }}</el-descriptions-item>
          <el-descriptions-item label="客户编码">{{ detailForm.customerCode }}</el-descriptions-item>
          <el-descriptions-item label="送货人员">{{ detailForm.deliveryPerson }}</el-descriptions-item>
          <el-descriptions-item label="送货日期">{{ parseTime(detailForm.deliveryDate, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
          <el-descriptions-item label="总金额">¥{{ detailForm.totalAmount ? detailForm.totalAmount.toFixed(2) : '0.00' }}</el-descriptions-item>
          <el-descriptions-item label="送货状态">
            <dict-tag :options="dict.type.sys_delivery_status" :value="detailForm.deliveryStatus"/>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ parseTime(detailForm.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ detailForm.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider content-position="left">送货明细</el-divider>
        <el-table :data="detailForm.deliveryDetailList" border>
          <el-table-column type="index" label="序号" width="60" align="center" />
          <el-table-column label="物料编码" prop="materialCode" width="120" />
          <el-table-column label="物料名称" prop="materialName" min-width="150" />
          <el-table-column label="数量" prop="quantity" width="100" align="center">
            <template slot-scope="scope">
              {{ scope.row.quantity }}{{ scope.row.unit }}
            </template>
          </el-table-column>
          <el-table-column label="单价" prop="unitPrice" width="100" align="center">
            <template slot-scope="scope">
              ¥{{ scope.row.unitPrice ? scope.row.unitPrice.toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
          <el-table-column label="小计" prop="totalPrice" width="120" align="center">
            <template slot-scope="scope">
              ¥{{ scope.row.totalPrice ? scope.row.totalPrice.toFixed(2) : '0.00' }}
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-drawer>

    <!-- 打印模板 (隐藏) -->
    <div id="printTemplate" style="display: none;">
      <div class="print-container">
        <div v-for="(page, pageIndex) in printPages" :key="pageIndex" class="print-page">
          <!-- 页面头部 -->
          <div class="print-header">
            <h2 style="text-align: center; margin: 0 0 20px 0; font-size: 24px; font-weight: bold;">送货单</h2>
            <div class="header-info">
              <div class="header-row">
                <span><strong>送货单编号：</strong>{{ detailForm.deliveryNo }}</span>
                <span><strong>送货日期：</strong>{{ parseTime(detailForm.deliveryDate, '{y}-{m}-{d} {h}:{i}') }}</span>
              </div>
              <div class="header-row">
                <span><strong>客户名称：</strong>{{ detailForm.customerName }}</span>
                <span><strong>客户编码：</strong>{{ detailForm.customerCode }}</span>
              </div>
              <div class="header-row">
                <span><strong>送货人员：</strong>{{ detailForm.deliveryPerson }}</span>
                <span><strong>送货状态：</strong>{{ getDeliveryStatusText(detailForm.deliveryStatus) }}</span>
              </div>
            </div>
          </div>

          <!-- 明细表格 -->
          <div class="print-table">
            <table border="1" cellspacing="0" cellpadding="8" style="width: 100%; border-collapse: collapse;">
              <thead>
                <tr style="background-color: #f5f7fa;">
                  <th style="width: 8%; text-align: center;">序号</th>
                  <th style="width: 15%; text-align: center;">物料编码</th>
                  <th style="width: 30%; text-align: center;">物料名称</th>
                  <th style="width: 12%; text-align: center;">数量</th>
                  <th style="width: 8%; text-align: center;">单位</th>
                  <th style="width: 12%; text-align: center;">单价</th>
                  <th style="width: 15%; text-align: center;">小计</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="(detail, index) in page.details" :key="index">
                  <td style="text-align: center;">{{ page.startIndex + index + 1 }}</td>
                  <td style="text-align: center;">{{ detail.materialCode }}</td>
                  <td style="padding-left: 8px;">{{ detail.materialName }}</td>
                  <td style="text-align: center;">{{ detail.quantity }}</td>
                  <td style="text-align: center;">{{ detail.unit }}</td>
                  <td style="text-align: right; padding-right: 8px;">¥{{ detail.unitPrice ? detail.unitPrice.toFixed(2) : '0.00' }}</td>
                  <td style="text-align: right; padding-right: 8px;">¥{{ detail.totalPrice ? detail.totalPrice.toFixed(2) : '0.00' }}</td>
                </tr>
                <!-- 填充空行到20行 -->
                <tr v-for="n in (20 - page.details.length)" :key="'empty-' + n" v-if="pageIndex === printPages.length - 1">
                  <td style="text-align: center; height: 25px;">&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                  <td>&nbsp;</td>
                </tr>
              </tbody>
            </table>
          </div>

          <!-- 页面底部信息 (仅在最后一页显示) -->
          <div v-if="pageIndex === printPages.length - 1" class="print-footer">
            <div class="footer-info">
              <div class="footer-row">
                <span><strong>总金额：¥{{ detailForm.totalAmount ? detailForm.totalAmount.toFixed(2) : '0.00' }}</strong></span>
              </div>
              <div class="footer-row" v-if="detailForm.remark">
                <span><strong>备注：</strong>{{ detailForm.remark }}</span>
              </div>
              <div class="signature-area">
                <div class="signature-item">
                  <span>送货人签字：</span>
                  <span class="signature-line">_________________</span>
                </div>
                <div class="signature-item">
                  <span>收货人签字：</span>
                  <span class="signature-line">_________________</span>
                </div>
                <div class="signature-item">
                  <span>日期：</span>
                  <span class="signature-line">_________________</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 页码 (多页时显示) -->
          <div v-if="printPages.length > 1" class="page-number">
            第 {{ pageIndex + 1 }} 页 / 共 {{ printPages.length }} 页
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { listDelivery, getDelivery, delDelivery, addDelivery, updateDelivery, updateDeliveryStatus } from "@/api/test/delivery";
import { listCustomer, optionselect as customerOptionselect } from "@/api/test/customer";
import { listMaterial, optionselect as materialOptionselect } from "@/api/test/material";

export default {
  name: "Delivery",
  dicts: ['sys_delivery_status', 'sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 送货单主表表格数据
      deliveryList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 详情弹出层
      detailOpen: false,
      // 送货日期时间范围
      daterangeDeliveryDate: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        deliveryNo: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        deliveryPerson: null,
        deliveryDate: null,
        deliveryStatus: null,
        status: null,
        orderByColumn: 'create_time',
        isAsc: 'desc'
      },
      // 表单参数
      form: {},
      // 详情表单
      detailForm: {},
      // 表单校验
      rules: {
        customerId: [
          { required: true, message: "客户不能为空", trigger: "change" }
        ],
        deliveryDate: [
          { required: true, message: "送货日期不能为空", trigger: "blur" }
        ],
        deliveryStatus: [
          { required: true, message: "送货状态不能为空", trigger: "change" }
        ]
      },
      // 客户选项
      customerOptions: [],
      // 物料选项
      materialOptions: [],
      // 原始明细数据（用于比较变更）
      originalDetailList: [],
      // 总金额显示
      totalAmountDisplay: "0.00",
      // 打印分页数据
      printPages: []
    };
  },
  created() {
    this.getList();
    this.getCustomerOptions();
    this.getMaterialOptions();
  },
  methods: {
    /** 查询送货单主表列表 */
    getList() {
      this.loading = true;
      this.queryParams.params = {};
      if (null != this.daterangeDeliveryDate && '' != this.daterangeDeliveryDate) {
        this.queryParams.params["beginDeliveryDate"] = this.daterangeDeliveryDate[0];
        this.queryParams.params["endDeliveryDate"] = this.daterangeDeliveryDate[1];
      }
      listDelivery(this.queryParams).then(response => {
        this.deliveryList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.detailOpen = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        deliveryId: null,
        deliveryNo: null,
        customerId: null,
        customerCode: null,
        customerName: null,
        deliveryPerson: null,
        deliveryDate: null,
        totalAmount: 0,
        deliveryStatus: "1",
        status: "0",
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deliveryDetailList: []
      };
      this.detailForm = {};
      this.originalDetailList = [];
      this.totalAmountDisplay = "0.00";
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.daterangeDeliveryDate = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deliveryId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.handleAddDetail(); // 默认添加一行明细
      this.open = true;
      this.title = "添加送货单主表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deliveryId = row.deliveryId || this.ids
      getDelivery(deliveryId).then(response => {
        this.form = response.data;
        
        // 保存原始明细数据
        this.originalDetailList = JSON.parse(JSON.stringify(response.data.deliveryDetailList || []));
        
        // 标记现有明细
        if (this.form.deliveryDetailList) {
          this.form.deliveryDetailList.forEach(item => {
            item._isNew = false; // 标记为非新增
          });
        } else {
          this.form.deliveryDetailList = [];
        }
        
        this.calculateTotalAmount();
        this.open = true;
        this.title = "修改送货单主表";
      });
    },
    /** 详情按钮操作 */
    handleDetail(row) {
      this.reset();
      const deliveryId = row.deliveryId;
      getDelivery(deliveryId).then(response => {
        this.detailForm = response.data;
        this.detailOpen = true;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 校验明细数据
          if (!this.form.deliveryDetailList || this.form.deliveryDetailList.length === 0) {
            this.$modal.msgWarning("请至少添加一条送货明细");
            return;
          }
          
          // 校验明细完整性
          for (let i = 0; i < this.form.deliveryDetailList.length; i++) {
            const detail = this.form.deliveryDetailList[i];
            if (!detail.materialId || !detail.quantity || !detail.unitPrice) {
              this.$modal.msgWarning(`第${i + 1}行明细数据不完整，请检查物料、数量、单价`);
              return;
            }
          }
          
          // 重新计算金额确保准确性
          this.calculateTotalAmount();
          
          if (this.form.deliveryId != null) {
            updateDelivery(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDelivery(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deliveryIds = row.deliveryId || this.ids;
      this.$modal.confirm('是否确认删除送货单编号为"' + deliveryIds + '"的数据项？').then(function() {
        return delDelivery(deliveryIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      let queryParams = { ...this.queryParams };
      if (null != this.daterangeDeliveryDate && '' != this.daterangeDeliveryDate) {
        queryParams.params = {
          beginDeliveryDate: this.daterangeDeliveryDate[0],
          endDeliveryDate: this.daterangeDeliveryDate[1]
        };
      }
      this.download('test/delivery/export', queryParams, `delivery_${new Date().getTime()}.xlsx`)
    },
    /** 状态修改 */
    handleStatusChange(row) {
      let text = row.status === "0" ? "启用" : "停用";
      this.$modal.confirm('确认要"' + text + '""' + row.deliveryNo + '"送货单吗？').then(function() {
        return updateDeliveryStatus({
          deliveryId: row.deliveryId,
          status: row.status
        });
      }).then(() => {
        this.$modal.msgSuccess(text + "成功");
      }).catch(function() {
        row.status = row.status === "0" ? "1" : "0";
      });
    },
    /** 更多操作命令 */
    handleCommand(command, row) {
      let statusMap = {
        'delivery': { status: '2', text: '送货中' },
        'delivered': { status: '3', text: '已送达' },
        'signed': { status: '4', text: '已签收' }
      };
      
      let config = statusMap[command];
      if (config) {
        this.$modal.confirm('确认要将"' + row.deliveryNo + '"状态更改为"' + config.text + '"吗？').then(() => {
          return updateDeliveryStatus({
            deliveryId: row.deliveryId,
            deliveryStatus: config.status
          });
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("状态更新成功");
        }).catch(() => {});
      }
    },

    /** 获取客户选项 */
    getCustomerOptions() {
      customerOptionselect().then(response => {
        this.customerOptions = response.data || [];
      });
    },
    /** 获取物料选项 */
    getMaterialOptions() {
      materialOptionselect().then(response => {
        this.materialOptions = response.data || [];
      });
    },
    /** 客户选择变更 */
    handleCustomerChange(customerId) {
      if (customerId) {
        const customer = this.customerOptions.find(item => item.customerId === customerId);
        if (customer) {
          this.form.customerCode = customer.customerCode;
          this.form.customerName = customer.customerName;
        }
      } else {
        this.form.customerCode = null;
        this.form.customerName = null;
      }
    },
    /** 添加明细 */
    handleAddDetail() {
      const newDetail = {
        detailId: null,           // 新增明细ID为空
        deliveryId: this.form.deliveryId,
        materialId: null,
        materialCode: '',
        materialName: '',
        quantity: 1,
        unit: '',
        unitPrice: 0,
        totalPrice: 0,
        _isNew: true              // 标记为新增
      };
      
      if (!this.form.deliveryDetailList) {
        this.form.deliveryDetailList = [];
      }
      
      this.form.deliveryDetailList.push(newDetail);
    },
    /** 删除明细 */
    handleDeleteDetail(index) {
      if (this.form.deliveryDetailList.length <= 1) {
        this.$modal.msgWarning("至少保留一条明细记录");
        return;
      }
      
      const detail = this.form.deliveryDetailList[index];
      
      // 如果是已存在的明细，提示确认
      if (detail.detailId && !detail._isNew) {
        this.$modal.confirm('确认删除该条明细记录？删除后将在保存时生效。').then(() => {
          this.form.deliveryDetailList.splice(index, 1);
          this.calculateTotalAmount();
        });
      } else {
        // 新增的明细直接删除
        this.form.deliveryDetailList.splice(index, 1);
        this.calculateTotalAmount();
      }
    },
    /** 物料选择变更 */
    handleMaterialChange(index) {
      const materialId = this.form.deliveryDetailList[index].materialId;
      if (materialId) {
        // 检查物料是否重复
        const isDuplicate = this.form.deliveryDetailList.some((item, idx) => {
          return idx !== index && item.materialId === materialId;
        });
        
        if (isDuplicate) {
          this.$modal.msgWarning("该物料已存在，请选择其他物料");
          // 清空当前选择
          this.$set(this.form.deliveryDetailList[index], 'materialId', null);
          this.clearMaterialFields(index);
          return;
        }
        
        const material = this.materialOptions.find(item => item.materialId === materialId);
        if (material) {
          // 使用$set确保Vue能检测到变化
          this.$set(this.form.deliveryDetailList[index], 'materialCode', material.materialCode);
          this.$set(this.form.deliveryDetailList[index], 'materialName', material.materialName);
          this.$set(this.form.deliveryDetailList[index], 'unit', material.unitOfMeasure || '');
          this.$set(this.form.deliveryDetailList[index], 'unitPrice', material.salePrice || 0);
          
          this.calculateRowTotal(index);
        }
      } else {
        // 清空选择时也清空相关字段
        this.clearMaterialFields(index);
      }
    },
    /** 清空物料相关字段 */
    clearMaterialFields(index) {
      this.$set(this.form.deliveryDetailList[index], 'materialCode', '');
      this.$set(this.form.deliveryDetailList[index], 'materialName', '');
      this.$set(this.form.deliveryDetailList[index], 'unit', '');
      this.$set(this.form.deliveryDetailList[index], 'unitPrice', 0);
      this.calculateRowTotal(index);
    },
    /** 检查物料是否已被其他行选择 */
    isMaterialSelected(materialId, currentIndex) {
      if (!this.form.deliveryDetailList || !materialId) {
        return false;
      }
      return this.form.deliveryDetailList.some((item, index) => {
        return index !== currentIndex && item.materialId === materialId;
      });
    },
    /** 计算行小计 */
    calculateRowTotal(index) {
      const row = this.form.deliveryDetailList[index];
      if (row.quantity && row.unitPrice) {
        row.totalPrice = (row.quantity * row.unitPrice);
      } else {
        row.totalPrice = 0;
      }
      this.calculateTotalAmount();
    },
    /** 计算总金额 */
    calculateTotalAmount() {
      let total = 0;
      if (this.form.deliveryDetailList) {
        this.form.deliveryDetailList.forEach(item => {
          if (item.totalPrice) {
            total += parseFloat(item.totalPrice);
          }
        });
      }
      this.totalAmountDisplay = total.toFixed(2);
      this.form.totalAmount = total;
    },
    /** 打印送货单 */
    handlePrint() {
      if (!this.detailForm.deliveryDetailList || this.detailForm.deliveryDetailList.length === 0) {
        this.$modal.msgWarning("没有明细数据可打印");
        return;
      }
      
      // 准备打印数据
      this.preparePrintData();
      
      // 延迟执行打印，确保Vue渲染完成
      this.$nextTick(() => {
        this.doPrint();
      });
    },
    /** 准备打印数据 - 实现分页逻辑 */
    preparePrintData() {
      const detailList = this.detailForm.deliveryDetailList || [];
      const pageSize = 20; // 每页最多20条明细
      this.printPages = [];
      
      for (let i = 0; i < detailList.length; i += pageSize) {
        const pageDetails = detailList.slice(i, i + pageSize);
        this.printPages.push({
          details: pageDetails,
          startIndex: i // 记录起始索引，用于计算序号
        });
      }
      
      // 如果没有明细，至少创建一个空页面
      if (this.printPages.length === 0) {
        this.printPages.push({
          details: [],
          startIndex: 0
        });
      }
    },
    /** 获取送货状态文本 */
    getDeliveryStatusText(status) {
      const statusMap = {
        '1': '待送货',
        '2': '送货中', 
        '3': '已送达',
        '4': '已签收'
      };
      return statusMap[status] || '未知状态';
    },
    /** 执行打印 */
    doPrint() {
      // 获取打印内容
      const printContent = document.getElementById('printTemplate').innerHTML;
      
      // 创建新窗口进行打印
      const printWindow = window.open('', '_blank');
      printWindow.document.write(`
        <!DOCTYPE html>
        <html>
        <head>
          <meta charset="utf-8">
          <title>送货单打印</title>
          <style>
            * {
              margin: 0;
              padding: 0;
              box-sizing: border-box;
            }
            
            body {
              font-family: "Microsoft YaHei", Arial, sans-serif;
              font-size: 12px;
              line-height: 1.4;
              color: #333;
            }
            
            .print-container {
              width: 100%;
            }
            
                         .print-page {
               width: 210mm;
               min-height: 297mm;
               margin: 0 auto;
               padding: 15mm;
               page-break-after: always;
               background: white;
             }
            
            .print-page:last-child {
              page-break-after: auto;
            }
            
                         .print-header {
               margin-bottom: 15px;
             }
             
             .header-info {
               margin-top: 10px;
             }
            
            .header-row {
              display: flex;
              justify-content: space-between;
              margin-bottom: 8px;
              font-size: 13px;
            }
            
                         .print-table {
               margin-bottom: 15px;
             }
            
                         .print-table table {
               width: 100%;
               border-collapse: collapse;
               font-size: 10px;
             }
             
             .print-table th,
             .print-table td {
               border: 1px solid #333;
               padding: 4px;
               vertical-align: middle;
               line-height: 1.2;
             }
            
            .print-table th {
              background-color: #f0f0f0;
              font-weight: bold;
              text-align: center;
            }
            
            .print-footer {
              margin-top: 30px;
            }
            
            .footer-row {
              margin-bottom: 15px;
              font-size: 14px;
            }
            
            .signature-area {
              margin-top: 40px;
              display: flex;
              justify-content: space-between;
            }
            
            .signature-item {
              font-size: 13px;
            }
            
            .signature-line {
              display: inline-block;
              width: 120px;
              border-bottom: 1px solid #333;
              margin-left: 10px;
            }
            
            .page-number {
              position: absolute;
              bottom: 10mm;
              right: 20mm;
              font-size: 10px;
              color: #666;
            }
            
            @media print {
              body {
                -webkit-print-color-adjust: exact;
                print-color-adjust: exact;
              }
              
              .print-page {
                margin: 0;
                padding: 15mm;
                page-break-after: always;
              }
              
              .print-page:last-child {
                page-break-after: auto;
              }
              
              @page {
                size: A4;
                margin: 0;
              }
            }
          </style>
        </head>
        <body>
          ${printContent}
        </body>
        </html>
      `);
      
      printWindow.document.close();
      
      // 等待内容加载完成后执行打印
      printWindow.onload = function() {
        printWindow.focus();
        printWindow.print();
        printWindow.close();
      };
    }
  }
};
</script>

<style scoped>
/* 物料下拉框选项样式 */
.material-option-content {
  position: relative;
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  width: 100%;
  padding: 2px 0;
}

.material-name {
  flex: 1;
  margin-right: 15px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 180px;
}

.material-info {
  flex-shrink: 0;
  text-align: right;
  color: #8492a6;
  font-size: 11px;
  line-height: 1.3;
  min-width: 80px;
}

.material-code {
  margin-bottom: 2px;
  font-weight: 500;
}

.material-price {
  color: #67c23a;
  font-weight: 500;
}

.material-disabled {
  opacity: 0.6;
  background-color: #f5f7fa !important;
}

.material-selected-tag {
  position: absolute;
  right: 5px;
  top: 50%;
  transform: translateY(-50%);
  background-color: #e6a23c;
  color: white;
  font-size: 10px;
  padding: 2px 6px;
  border-radius: 10px;
  line-height: 1;
}

/* 打印模板样式 */
#printTemplate {
  display: none !important;
}
</style>

<style>
/* 全局样式 - 下拉框弹出层 */
.material-select-dropdown {
  min-width: 320px !important;
}

.material-select-dropdown .el-select-dropdown__item {
  height: auto !important;
  line-height: normal !important;
  padding: 8px 20px !important;
}
</style> 